/* eslint-disable no-else-return */
/* eslint-disable indent */
/* eslint-disable no-unneeded-ternary */
/* eslint-disable max-lines */
import React from 'react';
import PropTypes from 'prop-types';
import {Card, Button, Row, Col, Form, Spin, Table, Popconfirm, message as msg, Switch, Collapse} from 'antd';
import routes from './routes';
import {updateValidator} from './validator';
import Return from '../common/Return';
import {FORM_OPTIONS, TABLE, FIXED_COLUMN_WIDTH} from '../constants';
import {getDetail, updateData} from './api';
import {agentKind, currency} from '../Enum';
import styles from './style.css';
import {conventEnumValueToString} from '../utils';
import WrappedSelect from '../common/WrappedSelect';
import {uuid} from './utils';
import PersonnelSelectPanel from './PersonnelSelectPanel';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import LocalizeInputNumber from '../common/LocalizeInputNumber';
import WrappedInputNumber from '../common/WrappedInputNumber';
import InputPercent from '../common/InputPercent';
import InputAmount from '../common/InputAmount';
import WrappedDatePicker from '../common/WrappedDatePicker';
import ImportPanel from './ImportPanel';
import {injectIntl, language} from './intl';
import moment from 'moment';
import PartSelectPanel from './PartSelectPanel';
import SearchInput from 'Shared/components/SearchInput';
import TextInput from 'Shared/components/TextInput';
const FormItem = Form.Item;
const {Panel} = Collapse;
const currencyList = currency.toList(language);
export class UpdatePanel extends React.PureComponent {
    state = {
        isValidate: false,
        hasOperat: false,
        loading: false,
        showDealerSelectPanel: false,
        showPersonnelSelectPanel: false,
        detailId: '',
        data: {},
        dealerServiceInformation: [],
        dealerPersonnel: [],
        partPriceCoefficientDetail: [],
        specialPartPriceCoefficient: [],
        showImportPanel: false,
        showPartSelectPanel: false,
    }
   
    componentDidMount() {
        if(this.props.id)
            this.getDetailInfo();
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    getDetailInfo = () => {
        const id = this.props.id;
        this.setState({loading: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data,
                        dealerServiceInformation: res.data.dealerServiceInformations || [],
                        dealerPersonnel: res.data.dealerPersonnels || [],
                        partPriceCoefficientDetail: res.data.partPriceCoefficientDetail || [],
                        specialPartPriceCoefficient: res.data.specialPartPriceCoefficient || [],
                    });
                else
                    this.setState(({
                        loading: false
                    }));
            });
    }
    onSubmit = () => {
        this.setState({
            loading: true
        });
        const {data, dealerServiceInformation, dealerPersonnel, partPriceCoefficientDetail, specialPartPriceCoefficient} = this.state;
        const newPartPriceCoefficientDetail = (partPriceCoefficientDetail || []).filter(v => v.isNow);
        const dealerPersonnelIds = [];
        if(dealerPersonnel)
            for(const d of dealerPersonnel)
                dealerPersonnelIds.push(d.id);
        const condition = {
            rowVersion: data.rowVersion,
            dealerServiceInformation: (dealerServiceInformation || []).map(v => ({
                brandId: v.brandId,
                tradeMethodId: v.tradeMethodId,
                currency: v.currency,
                cbuIntervalDate: v.cbuIntervalDate,
                kdIntervalDate: v.kdIntervalDate,
                exAuthorizatedLimit: v.exAuthorizatedLimit,
                price: v.price,
                mgmtFeeRate: v.mgmtFeeRate,
                isNeedApproved: v.isNeedApproved,
                isNeedPicture: v.isNeedPicture,
                submitTimeLimit: v.submitTimeLimit,
                claimPITitle: v.claimPITitle
            })),
            dealerPersonnel: dealerPersonnelIds,
            partPriceCoefficientDetail: (newPartPriceCoefficientDetail || []).map(v => ({
                brandId: v.brandId,
                priceRate: v.priceRate,
            })),
            specialPartPriceCoefficient: (specialPartPriceCoefficient || []).map(v => ({
                brandId: v.brandId,
                partId: v.partId,
                priceRate: v.priceRate,
                startTime: v.startTime,
                endTime: v.endTime
            })),
        };

        const isValid = updateValidator(condition);
        if(!isValid) {
            this.setState({
                isValidate: true,
                loading: false
            });
            return;
        }
        updateData(data.id, condition).then(res => {
            if(res.ok)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onClickReturnBtn = () => {
        this.props.onCancel();
    }
    onClickAddDetailBtn = () => {
        const details = this.state.dealerServiceInformation;
        this.setState({
            dealerServiceInformation: [
                ...details,
                {
                    id: uuid(),
                    isNeedApproved: null
                }
            ],
            hasOperat: true
        });
    };
    onClickAddPartPriceCoefficientBtn = () => {
        const details = this.state.partPriceCoefficientDetail;
        this.setState({
            partPriceCoefficientDetail: [
                ...details,
                {
                    id: uuid(),
                    year: moment().format('YYYY'),
                    month: moment().format('M'),
                    isNow: true,
                }
            ],
            hasOperat: true
        });
    };
    onClickAddSpecialPartPriceCoefficientBtn = () => {
        const details = this.state.specialPartPriceCoefficient;
        this.setState({
            specialPartPriceCoefficient: [
                ...details,
                {
                    id: uuid(),
                }
            ],
            hasOperat: true
        });
    };
    onClickPartSelectPanel = id => {
        this.setState({
            showPartSelectPanel: true,
            detailId: id
        });
    }
    onClosePartSelectPanel = () => {
        this.setState({showPartSelectPanel: false});
    }
    onBrandChange = (brandId, id) => {
        const details = this.state.dealerServiceInformation || [];
        const index = details.findIndex(v => v.brandId === brandId);
        if(index === 0)
            return msg.warn(this.props.intl.formatMessage({
                id: 'updatePanel.message.brand',
                defaultMessage: '已存在该品牌'
            }));
        const tmp = details.map(d => {
            const index = details.findIndex(v => v.brandId === brandId);
            if(d.id === id && index === -1)
                return Object.assign({}, d, {
                    brandId,
                });
            return d;
        });
        this.setState({
            dealerServiceInformation: tmp,
            hasOperat: true
        });
    }
    onPartPriceCoefficientBrandChange = (brandId, id) => {
        const details = this.state.partPriceCoefficientDetail || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    brandId,
                });
            return d;
        });
        this.setState({
            partPriceCoefficientDetail: tmp,
            hasOperat: true
        });
    }
    onSpecialPartPriceCoefficientBrandChange = (brandId, id) => {
        const details = this.state.specialPartPriceCoefficient || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    brandId,
                });
            return d;
        });
        this.setState({
            specialPartPriceCoefficient: tmp,
            hasOperat: true
        });
    }
    onTradeMethodChange = (tradeMethodId, id) => {
        const details = this.state.dealerServiceInformation || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    tradeMethodId,
                });
            return d;
        });
        this.setState({
            dealerServiceInformation: tmp,
            hasOperat: true
        });
    }
    onDealerPartInformationChange = (value, name, id) => {
        const details = this.state.dealerServiceInformation || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    [name]: value,
                });
            return d;
        });
        this.setState({
            dealerServiceInformation: tmp,
            hasOperat: true
        });
    }
    onPartPriceCoefficientChange = (value, name, id) => {
        const details = this.state.partPriceCoefficientDetail || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    [name]: value,
                });
            return d;
        });
        this.setState({
            partPriceCoefficientDetail: tmp,
            hasOperat: true
        });
    }
    onSpecialPartPriceCoefficientChange = (value, name, id) => {
        const details = this.state.specialPartPriceCoefficient || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    [name]: value,
                });
            return d;
        });
        this.setState({
            specialPartPriceCoefficient: tmp,
            hasOperat: true
        });
    }
    onDeleteDetail = e => {
        const id = e.target.dataset.id;
        const dealerServiceInformation = this.state.dealerServiceInformation.filter(p => p.id !== id);
        this.setState({
            dealerServiceInformation,
            hasOperat: true
        });
    }
    onPartPriceCoefficientDetailDelete = e => {
        const id = e.target.dataset.id;
        const partPriceCoefficientDetail = this.state.partPriceCoefficientDetail.filter(p => p.id !== id);
        this.setState({
            partPriceCoefficientDetail,
            hasOperat: true
        });
    }
    onSpecialPartPriceCoefficientDeleteDetail = e => {
        const id = e.target.dataset.id;
        const specialPartPriceCoefficient = this.state.specialPartPriceCoefficient.filter(p => p.id !== id);
        this.setState({
            specialPartPriceCoefficient,
            hasOperat: true
        });
    }
    onDeleteAll = () => {
        this.setState({
            dealerServiceInformation: [],
            hasOperat: true
        });
    }
    onPartPriceCoefficientDetailDeleteAll = () => {
        this.setState({
            partPriceCoefficientDetail: [],
            hasOperat: true
        });
    }
    onSpecialPartPriceCoefficientDeleteAll = () => {
        this.setState({
            specialPartPriceCoefficient: [],
            hasOperat: true
        });
    }
    onCloseDealerSelectPanel= () => {
        this.setState({showDealerSelectPanel: false});
    }
    onClickSearchPersonnelBtn = () => {
        this.setState({
            showPersonnelSelectPanel: true,
        });
    }
    onPersonnelDeleteAddedItem = e => {
        const addedItemId = e.target.dataset.id;
        const tmp = this.state.dealerPersonnel.filter(d => d.id !== addedItemId);
        this.setState({
            dealerPersonnel: [...tmp],
            hasOperat: true
        });
    }
    onPersonnelDeleteAll = () => {
        this.setState({
            dealerPersonnel: [],
            hasOperat: true
        });
    }
    onClosePersonnelSelectPanel = () => {
        this.setState({showPersonnelSelectPanel: false});
    }
    onSelectAddedPersonnel = records => {
        const addedItems = this.state.dealerPersonnel || [];
        records.forEach(r => {
            const index = addedItems.findIndex(v => v.id === r.id);
            if(index === -1)
                addedItems.push({
                    id: r.id,
                    userName: r.userName,
                    name: r.name,
                });
        });
        this.setState({
            dealerPersonnel: [...addedItems],
            hasOperat: true,
            showPersonnelSelectPanel: false
        });
    }

    onClickImportBtn = () => {
        this.setState({showImportPanel: true});
    }
    onCloseImportPanel = () => {
        this.setState({showImportPanel: false});
    }
    onImportChange = records => {
        if(records.payload) {
            const retailDetails = this.state.specialPartPriceCoefficient || [];
            records.payload.content.forEach(r => {
                const index = retailDetails.findIndex(v => v.partId === r.partId);
                if(index === -1)
                    retailDetails.push({
                        brandId: r.brandId,
                        brandCode: r.brandCode,
                        brandName: r.brandName,
                        partId: r.partId,
                        partCode: r.partCode,
                        partName: r.partName,
                        priceRate: r.priceRate,
                        startTime: r.startTime,
                        endTime: r.endTime
                    });
            });
            this.setState({
                specialPartPriceCoefficient: [...retailDetails],
                hasOperat: true,
                showImportPanel: false,
                isAlert: true
            });
        }
    }
    onSelectPart = record => {
        const details = this.state.specialPartPriceCoefficient || [];
        const tmp = details.map(d => {
            if(d.id === this.state.detailId)
                return Object.assign({}, d, {
                    partId: record.id,
                    partCode: record.code,
                    partName: record.name
                });
            return d;
        });
        this.setState({
            showPartSelectPanel: false,
            specialPartPriceCoefficient: tmp,
            hasOperat: true
        });
    }
    render() {
        const {data, dealerServiceInformation, dealerPersonnel, partPriceCoefficientDetail, specialPartPriceCoefficient, isValidate} = this.state;
        const {formatMessage} = this.props.intl;
        const {brands, tradeMethods} = this.props.initEnumData;
        const partInformationColumns = [{
            title: (<span className="ant-form-item-required">{formatMessage({
                id: 'updatePanel.column.brand',
                defaultMessage: '品牌'
            })}</span>
            ),
            width: 150,
            dataIndex: 'brandId',
            render: (text, record) => {
                const validate = !text && isValidate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <WrappedSelect
                            id={record.id}
                            options={brands}
                            value={record.brandId}
                            onChange={this.onBrandChange} />
                    </FormItem>
                );
            }
        }, {
            title: (<span className="ant-form-item-required">{formatMessage({
                id: 'updatePanel.column.tradeMethod',
                defaultMessage: '贸易方式'
            })}</span>
            ),
            width: 150,
            dataIndex: 'tradeMethodId',
            render: (text, record) => {
                const validate = !text && isValidate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <WrappedSelect
                            id={record.id}
                            options={tradeMethods}
                            value={record.tradeMethodId}
                            onChange={this.onTradeMethodChange} />
                    </FormItem>
                );
            }
        }, {
            title: (<span className="ant-form-item-required">{formatMessage({
                id: 'updatePanel.column.currency',
                defaultMessage: '币种'
            })}</span>
            ),
            width: 120,
            dataIndex: 'currency',
            render: (text, record) => {
                const validate = !text && isValidate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <WrappedSelect
                            id={record.id}
                            options={currencyList}
                            value={record.currency}
                            onChange={value => this.onDealerPartInformationChange(value, 'currency', record.id)}/>
                    </FormItem>
                );
            }
        }, {
            title: (<span className="ant-form-item-required">{formatMessage({
                id: 'updatePanel.column.cbuIntervalDate',
                defaultMessage: 'CBU间隔月份'
            })}</span>
            ),
            dataIndex: 'cbuIntervalDate',
            render: (text, record) => {
                const validate = !text && isValidate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <LocalizeInputNumber
                            name="cbuIntervalDate"
                            min={0}
                            value={record.cbuIntervalDate}
                            onChange={value => this.onDealerPartInformationChange(value, 'cbuIntervalDate', record.id)}/>
                    </FormItem>
                );
            }
        }, {
            title: (<span className="ant-form-item-required">{formatMessage({
                id: 'updatePanel.column.kdIntervalDate',
                defaultMessage: 'KD间隔月份'
            })}</span>
            ),
            dataIndex: 'kdIntervalDate',
            render: (text, record) => {
                const validate = !text && isValidate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <LocalizeInputNumber
                            name="kdIntervalDate"
                            min={0}
                            value={record.kdIntervalDate}
                            onChange={value => this.onDealerPartInformationChange(value, 'kdIntervalDate', record.id)}/>
                    </FormItem>
                );
            }
        }, {
            title: (<span className="ant-form-item-required">{formatMessage({
                id: 'updatePanel.column.exAuthorizatedLimit',
                defaultMessage: '备件超授权额度'
            })}</span>
            ),
            dataIndex: 'exAuthorizatedLimit',
            render: (text, record) => {
                const validate = !text && isValidate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <InputAmount
                            name="exAuthorizatedLimit"
                            value={record.exAuthorizatedLimit}
                            onBlur={value => this.onDealerPartInformationChange(value, 'exAuthorizatedLimit', record.id)}/>
                    </FormItem>
                );
            }
        }, {
            title: (<span className="ant-form-item-required">{formatMessage({
                id: 'updatePanel.column.isNeedApproved',
                defaultMessage: '是否需要自动审核'
            })}</span>
            ),
            dataIndex: 'isNeedApproved',
            render: (text, record) => {
                const validate = typeof text !== 'boolean' && isValidate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <Switch
                            checkedChildren={formatMessage({
                                id: 'yes',
                                defaultMessage: '是'
                            })}
                            unCheckedChildren={formatMessage({
                                id: 'no',
                                defaultMessage: '否'
                            })}
                            checked={text}
                            value={record.isNeedApproved}
                            id={record.id}
                            onChange={value => this.onDealerPartInformationChange(value, 'isNeedApproved', record.id)}/>
                    </FormItem>
                );
            }
        }, {
            title: (<span className="ant-form-item-required">{formatMessage({
                id: 'updatePanel.column.isNeedPicture',
                defaultMessage: '是否需要索赔图片'
            })}</span>
            ),
            dataIndex: 'isNeedPicture',
            render: (text, record) => {
                const validate = typeof text !== 'boolean' && isValidate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <Switch
                            checkedChildren={formatMessage({
                                id: 'yes',
                                defaultMessage: '是'
                            })}
                            unCheckedChildren={formatMessage({
                                id: 'no',
                                defaultMessage: '否'
                            })}
                            checked={text}
                            value={record.isNeedPicture}
                            id={record.id}
                            onChange={value => this.onDealerPartInformationChange(value, 'isNeedPicture', record.id)}/>
                    </FormItem>
                );
            }
        }, {
            title: (<span className="ant-form-item-required">{formatMessage({
                id: 'updatePanel.column.submitTimeLimit',
                defaultMessage: '索赔单提交时限'
            })}</span>
            ),
            dataIndex: 'submitTimeLimit',
            render: (text, record) => {
                const validate = !text && isValidate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <WrappedInputNumber
                            min={0}
                            precision={0}
                            name="submitTimeLimit"
                            value={record.submitTimeLimit}
                            onBlur={value => this.onDealerPartInformationChange(value, 'submitTimeLimit', record.id)} />
                    </FormItem>
                );
            }
        }, {
            title: (<span className="ant-form-item-required">{formatMessage({
                id: 'updatePanel.column.price',
                defaultMessage: '工时单价'
            })}</span>
            ),
            dataIndex: 'price',
            render: (text, record) => {
                const validate = !text && isValidate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <InputAmount
                            name="price"
                            value={record.price}
                            onBlur={value => this.onDealerPartInformationChange(value, 'price', record.id)}/>
                    </FormItem>
                );
            }
        }, {
            title: (<span className="ant-form-item-required">{formatMessage({
                id: 'updatePanel.column.mgmtFeeRate',
                defaultMessage: '备件管理费率'
            })}</span>
            ),
            dataIndex: 'mgmtFeeRate',
            render: (text, record) => {
                const validate = !text && isValidate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <InputPercent
                            name="mgmtFeeRate"
                            value={record.mgmtFeeRate}
                            onBlur={value => this.onDealerPartInformationChange(value, 'mgmtFeeRate', record.id)}/>
                    </FormItem>
                );
            }
        }, {
            title: (<span className="ant-form-item-required">{formatMessage({
                id: 'updatePanel.column.claimPITitle',
                defaultMessage: '索赔PI标题'
            })}</span>
            ),
            dataIndex: 'claimPITitle',
            render: (text, record) => {
                const validate = !text && isValidate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <TextInput
                            name="claimPITitle"
                            value={record.claimPITitle}
                            onBlur={value => this.onDealerPartInformationChange(value, 'claimPITitle', record.id)}/>
                    </FormItem>
                );
            }
        }, {
            title: dealerServiceInformation && dealerServiceInformation.length > 0
                ? (
                    <Popconfirm placement="topRight" title={formatMessage({
                        id: 'updatePanel.validation.isDelete',
                        defaultMessage: '是否确认全部删除？'
                    })} onConfirm={this.onDeleteAll} >
                        <a>{formatMessage({
                            id: 'updatePanel.validation.clear',
                            defaultMessage: '清空'
                        })}</a>
                    </Popconfirm>
                )
                : null,
            dataIndex: 'id',
            fixed: 'right',
            width: FIXED_COLUMN_WIDTH,
            render: text => <a data-id={text} onClick={this.onDeleteDetail}>{formatMessage({
                id: 'updatePanel.validation.delete',
                defaultMessage: '删除'
            })}</a>
        }];

        const personnelColumns = [{
            title: formatMessage({
                id: 'updatePanel.column.userName',
                defaultMessage: '编号'
            }),
            dataIndex: 'userName',
        }, {
            title: formatMessage({
                id: 'updatePanel.column.name',
                defaultMessage: '名称'
            }),
            dataIndex: 'name',
        }, {
            title: dealerPersonnel && dealerPersonnel.length ? (
                <WrappedPopconfirm
                    id="updatePanel.personnel.delete"
                    title={this.props.intl.formatMessage({
                        id: 'updatePanel.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    okText={this.props.intl.formatMessage({
                        id: 'updatePanel.personnel.popconfirm.confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={this.props.intl.formatMessage({
                        id: 'updatePanel.personnel.popconfirm.cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.onPersonnelDeleteAll}>
                    <a>
                        {this.props.intl.formatMessage({
                            id: 'updatePanel.personnel.deleteAll',
                            defaultMessage: '清空'
                        })}
                    </a>
                </WrappedPopconfirm>
            ) : null,
            dataIndex: 'action',
            fixed: 'right',
            width: FIXED_COLUMN_WIDTH,
            render: (text, record) => (
                <a onClick={this.onPersonnelDeleteAddedItem} data-id={record.id}>
                    {this.props.intl.formatMessage({
                        id: 'updatePanel.personnel.delete',
                        defaultMessage: '删除'
                    })}
                </a>
            )
        }];

        const partPriceCoefficientDetailColumns = [
            {
                title: (<span className="ant-form-item-required">{formatMessage({
                    id: 'updatePanel.partPriceCoefficientDetailColumns.brand',
                    defaultMessage: '品牌'
                })}</span>
                ),
                dataIndex: 'brandCode',
                width: 150,
                render: (text, record) => {
                    const validate = !record.brandId && isValidate ? {validateStatus: 'error'} : null;
                    return (
                        <FormItem {...validate}>
                            <WrappedSelect
                                id={record.id}
                                options={brands}
                                value={record.brandId}
                                onChange={this.onPartPriceCoefficientBrandChange} />
                        </FormItem>
                    );
                }
            },
            {
                title: (<span className="ant-form-item-required">{formatMessage({
                    id: 'updatePanel.partPriceCoefficientDetailColumns.year',
                    defaultMessage: '年份'
                })}</span>
                ),
                dataIndex: 'year',
            },
            {
                title: (<span className="ant-form-item-required">{formatMessage({
                    id: 'updatePanel.partPriceCoefficientDetailColumns.month',
                    defaultMessage: '月份'
                })}</span>
                ),
                dataIndex: 'month',
            },
            {
                title: (<span className="ant-form-item-required">{formatMessage({
                    id: 'updatePanel.partPriceCoefficientDetailColumns.priceRate',
                    defaultMessage: '价格系数'
                })}</span>
                ),
                dataIndex: 'priceRate',
                render: (text, record) => {
                    const validate = !text && isValidate ? {validateStatus: 'error'} : null;
                    return (
                        <FormItem {...validate}>
                            <InputPercent
                                name="priceRate"
                                min={0}
                                value={record.priceRate}
                                onBlur={value => this.onPartPriceCoefficientChange(value, 'priceRate', record.id)}/>
                        </FormItem>
                    );
                }
            },
            {
                title: formatMessage({
                    id: 'updatePanel.validation.operation',
                    defaultMessage: '操作'
                }),
                dataIndex: 'id',
                fixed: 'right',
                width: FIXED_COLUMN_WIDTH,
                render: (text, record) => record.isNow ? (<a data-id={text} onClick={this.onPartPriceCoefficientDetailDelete}>{formatMessage({
                    id: 'updatePanel.validation.delete',
                    defaultMessage: '删除'
                })}</a>) : formatMessage({
                    id: 'updatePanel.validation.noOperation',
                    defaultMessage: '不可删除'
                })
            }
        ];

        const specialPartPriceCoefficientColumns = [
            {
                title: (<span className="ant-form-item-required">{formatMessage({
                    id: 'updatePanel.specialPartPriceCoefficientColumns.brand',
                    defaultMessage: '品牌'
                })}</span>
                ),
                dataIndex: 'brandCode',
                width: 150,
                render: (text, record) => {
                    const validate = !record.brandId && isValidate ? {validateStatus: 'error'} : null;
                    return (
                        <FormItem {...validate}>
                            <WrappedSelect
                                id={record.id}
                                options={brands}
                                value={record.brandId}
                                onChange={this.onSpecialPartPriceCoefficientBrandChange} />
                        </FormItem>
                    );
                }
            },
            {
                title: (<span className="ant-form-item-required">{formatMessage({
                    id: 'updatePanel.specialPartPriceCoefficientColumns.partCode',
                    defaultMessage: '备件编号'
                })}</span>
                ),
                dataIndex: 'partId',
                width: 500,
                render: (text, record) => {
                    const validate = !text && isValidate ? {validateStatus: 'error'} : null;
                    return (
                        <FormItem {...validate}>
                            <SearchInput
                                disabled={true}
                                value={record.partId ? `(${record.partCode})${record.partName}` : ''}
                                id={record.id}
                                onClickSearchBtn={() => this.onClickPartSelectPanel(record.id)} />
                        </FormItem>
                    );
                }
            },
            {
                title: (<span className="ant-form-item-required">{formatMessage({
                    id: 'updatePanel.specialPartPriceCoefficientColumns.priceRate',
                    defaultMessage: '价格系数'
                })}</span>
                ),
                dataIndex: 'priceRate',
                render: (text, record) => {
                    const validate = !text && isValidate ? {validateStatus: 'error'} : null;
                    return (
                        <FormItem {...validate}>
                            <InputPercent
                                max={1}
                                min={0}
                                name="priceRate"
                                value={record.priceRate}
                                onBlur={value => this.onSpecialPartPriceCoefficientChange(value, 'priceRate', record.id)}/>
                        </FormItem>
                    );
                }
            },
            {
                title: (<span className="ant-form-item-required">{formatMessage({
                    id: 'updatePanel.specialPartPriceCoefficientColumns.startTime',
                    defaultMessage: '生效日期'
                })}</span>
                ),
                dataIndex: 'startTime',
                render: (text, record) => {
                    const validate = !text && isValidate ? {validateStatus: 'error'} : null;
                    return (
                        <FormItem {...validate}>
                            <WrappedDatePicker
                                name="startTime"
                                value={record.startTime}
                                onChange={value => this.onSpecialPartPriceCoefficientChange(value, 'startTime', record.id)} />
                        </FormItem>
                    );
                }
            },
            {
                title: (<span className="ant-form-item-required">{formatMessage({
                    id: 'updatePanel.specialPartPriceCoefficientColumns.endTime',
                    defaultMessage: '失效日期'
                })}</span>
                ),
                dataIndex: 'endTime',
                render: (text, record) => {
                    const validate = !text && isValidate ? {validateStatus: 'error'} : null;
                    return (
                        <FormItem {...validate}>
                            <WrappedDatePicker
                                name="endTime"
                                value={record.endTime}
                                onChange={value => this.onSpecialPartPriceCoefficientChange(value, 'endTime', record.id)} />
                        </FormItem>
                    );
                }
            },
            {
                title: specialPartPriceCoefficient && specialPartPriceCoefficient.length > 0
                    ? (
                        <Popconfirm placement="topRight" title={formatMessage({
                            id: 'updatePanel.validation.isDelete',
                            defaultMessage: '是否确认全部删除？'
                        })} onConfirm={this.onSpecialPartPriceCoefficientDeleteAll} >
                            <a>{formatMessage({
                                id: 'updatePanel.validation.clear',
                                defaultMessage: '清空'
                            })}</a>
                        </Popconfirm>
                    )
                    : null,
                dataIndex: 'id',
                fixed: 'right',
                width: FIXED_COLUMN_WIDTH,
                render: text => <a data-id={text} onClick={this.onSpecialPartPriceCoefficientDeleteDetail}>{formatMessage({
                    id: 'updatePanel.validation.delete',
                    defaultMessage: '删除'
                })}</a>
            }
        ];
        return (
            <div>
                <Spin spinning={this.state.loading}>
                        <Collapse className={styles.collapseMarginTop}>
                            <Panel header={<Form className="form-standard"><Row>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'updatePanel.data.code',
                                            defaultMessage: '编号'
                                        })}{...FORM_OPTIONS.item} >
                                            {data.code}
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'updatePanel.data.name',
                                            defaultMessage: '名称'
                                        })}{...FORM_OPTIONS.item} >
                                            {data.name}
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'updatePanel.data.shortCode',
                                            defaultMessage: '简码'
                                        })}{...FORM_OPTIONS.item} >
                                            {data.shortCode}
                                        </FormItem>
                                    </Col></Row></Form>}>
                                <Form className="form-standard">
                                    <Row>
                                        <Col {...FORM_OPTIONS.col}>
                                            <FormItem label={formatMessage({
                                                id: 'updatePanel.data.shortName',
                                                defaultMessage: '简称'
                                            })}{...FORM_OPTIONS.item} >
                                                {data.shortName}
                                            </FormItem>
                                        </Col>
                                        <Col {...FORM_OPTIONS.col}>
                                            <FormItem label={formatMessage({
                                                id: 'updatePanel.data.kind',
                                                defaultMessage: '客户分类'
                                            })}{...FORM_OPTIONS.item} >
                                                {conventEnumValueToString(agentKind, data.kind)}
                                            </FormItem>
                                        </Col>
                                        <Col {...FORM_OPTIONS.col}>
                                            <FormItem label={formatMessage({
                                                id: 'updatePanel.data.area',
                                                defaultMessage: '国际区域'
                                            })}{...FORM_OPTIONS.item} >
                                                {data.area}
                                            </FormItem>
                                        </Col>
                                        <Col {...FORM_OPTIONS.col}>
                                            <FormItem label={formatMessage({
                                                id: 'updatePanel.data.country',
                                                defaultMessage: '国家'
                                            })}{...FORM_OPTIONS.item} >
                                                {data.country}
                                            </FormItem>
                                        </Col>
                                        <Col {...FORM_OPTIONS.col}>
                                            <FormItem label={formatMessage({
                                                id: 'updatePanel.data.province',
                                                defaultMessage: '省份'
                                            })}{...FORM_OPTIONS.item} >
                                                {data.province}
                                            </FormItem>
                                        </Col>
                                        <Col {...FORM_OPTIONS.col}>
                                            <FormItem label={formatMessage({
                                                id: 'updatePanel.data.city',
                                                defaultMessage: '城市'
                                            })}{...FORM_OPTIONS.item} >
                                                {data.city}
                                            </FormItem>
                                        </Col>
                                        <Col {...FORM_OPTIONS.col}>
                                            <FormItem label={formatMessage({
                                                id: 'updatePanel.data.contactNumber',
                                                defaultMessage: '联系电话'
                                            })}{...FORM_OPTIONS.item} >
                                                {data.contactNumber}
                                            </FormItem>
                                        </Col>
                                        <Col {...FORM_OPTIONS.col}>
                                            <FormItem label={formatMessage({
                                                id: 'updatePanel.data.fax',
                                                defaultMessage: '传真'
                                            })}{...FORM_OPTIONS.item} >
                                                {data.fax}
                                            </FormItem>
                                        </Col>
                                        <Col {...FORM_OPTIONS.col}>
                                            <FormItem label={formatMessage({
                                                id: 'updatePanel.data.address',
                                                defaultMessage: '联系地址'
                                            })}{...FORM_OPTIONS.item} >
                                                {data.address}
                                            </FormItem>
                                        </Col>
                                        <Col {...FORM_OPTIONS.col}>
                                            <FormItem label={formatMessage({
                                                id: 'updatePanel.data.zipCode',
                                                defaultMessage: '邮政编码'
                                            })}{...FORM_OPTIONS.item} >
                                                {data.zipCode}
                                            </FormItem>
                                        </Col>
                                    </Row>
                                </Form>
                            </Panel>
                        </Collapse>
                    <Form className="form-standard">
                        <Card
                            title={formatMessage({
                                id: 'updatePanel.partInformationDetail',
                                defaultMessage: '服务站服务业务清单'
                            })}>
                            <Button
                                type="dashed"
                                icon="plus"
                                block
                                className={styles.plusBtn}
                                onClick={this.onClickAddDetailBtn}>
                                {formatMessage({
                                    id: 'updatePanel.operation.new',
                                    defaultMessage: '新增'
                                })}
                            </Button>
                            <Table
                                className="white-space-nowrap"
                                columns={partInformationColumns}
                                rowKey="id"
                                pagination={false}
                                dataSource={dealerServiceInformation}
                                {...TABLE} />
                        </Card>
                        <Card
                            title={formatMessage({
                                id: 'updatePanel.partPriceCoefficientDetail',
                                defaultMessage: '备件价格系数清单'
                            })}>
                            <Button
                                type="dashed"
                                icon="plus"
                                block
                                className={styles.plusBtn}
                                onClick={this.onClickAddPartPriceCoefficientBtn}>
                                {formatMessage({
                                    id: 'updatePanel.operation.new',
                                    defaultMessage: '新增'
                                })}
                            </Button>
                            <Table
                                className="white-space-nowrap"
                                columns={partPriceCoefficientDetailColumns}
                                rowKey="id"
                                pagination={false}
                                dataSource={partPriceCoefficientDetail}
                                {...TABLE} />
                        </Card>
                        <Card
                            title={formatMessage({
                                id: 'updatePanel. specialPartPriceCoefficient',
                                defaultMessage: '特殊件价格系数清单'
                            })}
                            extra={<div>
                                <Button
                                    size="small"
                                    onClick={this.onClickImportBtn}>
                                    {formatMessage({
                                        id: 'newPanel.operation.import',
                                        defaultMessage: '导入清单'
                                    })}
                                </Button>
                            </div>}>
                            <Button
                                type="dashed"
                                icon="plus"
                                block
                                className={styles.plusBtn}
                                onClick={this.onClickAddSpecialPartPriceCoefficientBtn}>
                                {formatMessage({
                                    id: 'updatePanel.operation.new',
                                    defaultMessage: '新增'
                                })}
                            </Button>
                            <Table
                                className="white-space-nowrap"
                                columns={specialPartPriceCoefficientColumns}
                                rowKey="id"
                                pagination={false}
                                dataSource={specialPartPriceCoefficient}
                                {...TABLE} />
                        </Card>
                        <Card
                            title={formatMessage({
                                id: 'updatePanel.personnel',
                                defaultMessage: '人员清单'
                            })}
                            extra={<Button size="small" onClick={this.onClickSearchPersonnelBtn}>
                                {this.props.intl.formatMessage({
                                    id: 'updatePanel.personnel.addDetail',
                                    defaultMessage: '新增清单'
                                })}</Button>}>
                            <Table
                                className="white-space-nowrap"
                                columns={personnelColumns}
                                rowKey="id"
                                pagination={false}
                                dataSource={dealerPersonnel}
                                {...TABLE} />
                        </Card>
                    </Form>
                    <Card>
                        <Row>
                            <Col className="col-align-right">
                                <Button key="submit"
                                    onClick={this.onSubmit}
                                    type="primary"
                                    loading={this.state.loading}>
                                    {formatMessage({
                                        id: 'addPanel.btn.submit',
                                        defaultMessage: '保存'
                                    })}</Button>
                            </Col>
                        </Row>
                    </Card>
                </Spin>
                {
                    this.state.showPersonnelSelectPanel &&
                    <PersonnelSelectPanel
                        selectKey={data.dealerId}
                        onCancel={this.onClosePersonnelSelectPanel}
                        onSelect={this.onSelectAddedPersonnel} />
                }
                {
                    this.state.showImportPanel &&
                    <ImportPanel
                        dealerId={this.props.id}
                        onCancel={this.onCloseImportPanel}
                        onImportChange={this.onImportChange} />
                }
                {
                    this.state.showPartSelectPanel &&
                    <PartSelectPanel
                        onCancel={this.onClosePartSelectPanel}
                        onSelect={this.onSelectPart} />
                }
                <div className="page-toolbar">
                    <Return
                        onConfirm={this.onClickReturnBtn}
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

UpdatePanel.propTypes = {
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    initEnumData: PropTypes.object,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {tableSearch} from './actions';
import {createSelector} from 'reselect';

const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `(${item.code}) ${item.name}`,
            value: item.id
        })) : [];
        const tradeMethods = initData.tradeMethods ? initData.tradeMethods.map(item => ({
            text: `(${item.code}) ${item.name}`,
            value: item.id
        })) : [];
        return {
            brands,
            tradeMethods,
            initData
        };
    }
);
const mapStateToProps = (state, props) => ({
    initEnumData: getinitEnumData(state),
    id: props.id,
});

const mapDispatchToProps = (dispatch, props) => ({
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(UpdatePanel));
